<template>
  <div class="exam-page">
    <!-- 考试头部信息 -->
    <div class="exam-header">
      <div class="exam-info">
        <h1>{{ exam.name }}</h1>
        <div class="exam-meta">
          <span class="meta-item">
            <i class="fas fa-clock"></i>
            考试时长：{{ exam.duration }} 分钟
          </span>
          <span class="meta-item">
            <i class="fas fa-list"></i>
            题目数量：{{ exam.questionCount }} 题
          </span>
          <span class="meta-item">
            <i class="fas fa-star"></i>
            总分：{{ exam.totalScore }} 分
          </span>
        </div>
      </div>
      
      <div class="exam-timer">
        <div class="timer-display" :class="{ warning: isTimeWarning, danger: isTimeDanger }">
          <i class="fas fa-hourglass-half"></i>
          <span class="time-text">{{ formatTime(remainingTime) }}</span>
        </div>
        <div class="timer-label">剩余时间</div>
      </div>
    </div>
    
    <!-- 考试进度 -->
    <div class="exam-progress">
      <div class="progress-info">
        <span class="progress-text">
          已答题：{{ answeredCount }} / {{ exam.questionCount }}
        </span>
        <span class="progress-percentage">
          {{ Math.round((answeredCount / exam.questionCount) * 100) }}%
        </span>
      </div>
      <el-progress 
        :percentage="Math.round((answeredCount / exam.questionCount) * 100)"
        :stroke-width="8"
        :show-text="false"
      />
    </div>
    
    <!-- 主要内容区域 -->
    <div class="exam-content">
      <!-- 题目导航 -->
      <div class="question-nav">
        <div class="nav-header">
          <h3>题目导航</h3>
          <el-button 
            size="small" 
            @click="toggleNavCollapse"
            :icon="navCollapsed ? Expand : Fold"
          >
            {{ navCollapsed ? '展开' : '收起' }}
          </el-button>
        </div>
        
        <div v-show="!navCollapsed" class="nav-content">
          <div class="nav-legend">
            <div class="legend-item">
              <span class="legend-dot answered"></span>
              <span>已答题</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot current"></span>
              <span>当前题</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot unanswered"></span>
              <span>未答题</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot marked"></span>
              <span>已标记</span>
            </div>
          </div>
          
          <div class="nav-grid">
            <button
              v-for="(question, index) in exam.questions"
              :key="question.id"
              class="nav-item"
              :class="{
                current: currentQuestionIndex === index,
                answered: isQuestionAnswered(index),
                marked: markedQuestions.includes(index)
              }"
              @click="goToQuestion(index)"
            >
              {{ index + 1 }}
            </button>
          </div>
        </div>
      </div>
      
      <!-- 题目内容 -->
      <div class="question-content">
        <div v-if="currentQuestion" class="question-card">
          <div class="question-header">
            <div class="question-number">
              第 {{ currentQuestionIndex + 1 }} 题
              <el-tag 
                :type="getQuestionTypeTag(currentQuestion.type)"
                size="small"
              >
                {{ getQuestionTypeLabel(currentQuestion.type) }}
              </el-tag>
            </div>
            
            <div class="question-actions">
              <el-button 
                size="small"
                :type="markedQuestions.includes(currentQuestionIndex) ? 'warning' : 'default'"
                @click="toggleMark"
              >
                <i class="fas fa-bookmark"></i>
                {{ markedQuestions.includes(currentQuestionIndex) ? '取消标记' : '标记题目' }}
              </el-button>
            </div>
          </div>
          
          <div class="question-score">
            <i class="fas fa-star"></i>
            {{ currentQuestion.score }} 分
          </div>
          
          <div class="question-text" v-html="currentQuestion.content"></div>
          
          <!-- 单选题 -->
          <div v-if="currentQuestion.type === 'single'" class="question-options">
            <el-radio-group 
              v-model="answers[currentQuestionIndex]"
              @change="saveAnswer"
            >
              <el-radio 
                v-for="(option, optionIndex) in currentQuestion.options"
                :key="optionIndex"
                :label="option.key"
                class="option-item"
              >
                <span class="option-key">{{ option.key }}.</span>
                <span class="option-text" v-html="option.text"></span>
              </el-radio>
            </el-radio-group>
          </div>
          
          <!-- 多选题 -->
          <div v-else-if="currentQuestion.type === 'multiple'" class="question-options">
            <el-checkbox-group 
              v-model="answers[currentQuestionIndex]"
              @change="saveAnswer"
            >
              <el-checkbox 
                v-for="(option, optionIndex) in currentQuestion.options"
                :key="optionIndex"
                :label="option.key"
                class="option-item"
              >
                <span class="option-key">{{ option.key }}.</span>
                <span class="option-text" v-html="option.text"></span>
              </el-checkbox>
            </el-checkbox-group>
          </div>
          
          <!-- 判断题 -->
          <div v-else-if="currentQuestion.type === 'boolean'" class="question-options">
            <el-radio-group 
              v-model="answers[currentQuestionIndex]"
              @change="saveAnswer"
            >
              <el-radio label="true" class="option-item">
                <span class="option-key">A.</span>
                <span class="option-text">正确</span>
              </el-radio>
              <el-radio label="false" class="option-item">
                <span class="option-key">B.</span>
                <span class="option-text">错误</span>
              </el-radio>
            </el-radio-group>
          </div>
          
          <!-- 填空题 -->
          <div v-else-if="currentQuestion.type === 'fill'" class="question-options">
            <div 
              v-for="(blank, blankIndex) in currentQuestion.blanks"
              :key="blankIndex"
              class="fill-item"
            >
              <label class="fill-label">第 {{ blankIndex + 1 }} 空：</label>
              <el-input
                v-model="answers[currentQuestionIndex][blankIndex]"
                placeholder="请输入答案"
                @input="saveAnswer"
              />
            </div>
          </div>
          
          <!-- 简答题 -->
          <div v-else-if="currentQuestion.type === 'essay'" class="question-options">
            <el-input
              v-model="answers[currentQuestionIndex]"
              type="textarea"
              :rows="8"
              placeholder="请输入您的答案..."
              @input="saveAnswer"
              show-word-limit
              :maxlength="currentQuestion.maxLength || 1000"
            />
          </div>
        </div>
        
        <!-- 题目导航按钮 -->
        <div class="question-navigation">
          <el-button 
            @click="previousQuestion"
            :disabled="currentQuestionIndex === 0"
            :icon="ArrowLeft"
          >
            上一题
          </el-button>
          
          <div class="nav-center">
            <span class="question-indicator">
              {{ currentQuestionIndex + 1 }} / {{ exam.questionCount }}
            </span>
          </div>
          
          <el-button 
            v-if="currentQuestionIndex < exam.questionCount - 1"
            @click="nextQuestion"
            :icon="ArrowRight"
          >
            下一题
          </el-button>
          
          <el-button 
            v-else
            type="primary"
            @click="showSubmitDialog"
            :icon="Check"
            :disabled="submitting"
          >
            提交考试
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 提交确认对话框 -->
    <el-dialog
      v-model="submitDialogVisible"
      title="提交考试"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="submit-summary">
        <div class="summary-item">
          <span class="label">考试名称：</span>
          <span class="value">{{ exam.name }}</span>
        </div>
        <div class="summary-item">
          <span class="label">总题数：</span>
          <span class="value">{{ exam.questionCount }} 题</span>
        </div>
        <div class="summary-item">
          <span class="label">已答题：</span>
          <span class="value" :class="{ warning: answeredCount < exam.questionCount }">
            {{ answeredCount }} 题
          </span>
        </div>
        <div class="summary-item">
          <span class="label">未答题：</span>
          <span class="value" :class="{ warning: unansweredCount > 0 }">
            {{ unansweredCount }} 题
          </span>
        </div>
        <div class="summary-item">
          <span class="label">已标记：</span>
          <span class="value">{{ markedQuestions.length }} 题</span>
        </div>
        <div class="summary-item">
          <span class="label">用时：</span>
          <span class="value">{{ formatTime(exam.duration * 60 - remainingTime) }}</span>
        </div>
      </div>
      
      <div v-if="unansweredCount > 0" class="submit-warning">
        <i class="fas fa-exclamation-triangle"></i>
        <span>您还有 {{ unansweredCount }} 道题未作答，确定要提交吗？</span>
      </div>
      
      <div class="submit-notice">
        <p><strong>注意：</strong></p>
        <ul>
          <li>提交后将无法修改答案</li>
          <li>系统将自动保存您的答题记录</li>
          <li>请确认所有答案无误后再提交</li>
        </ul>
      </div>
      
      <template #footer>
        <el-button @click="submitDialogVisible = false">继续答题</el-button>
        <el-button 
          type="primary" 
          @click="submitExamForm"
          :loading="submitting"
        >
          确认提交
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 自动保存提示 -->
    <div v-if="autoSaving" class="auto-save-indicator">
      <i class="fas fa-save"></i>
      <span>自动保存中...</span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, ArrowRight, Check, Expand, Fold } from '@element-plus/icons-vue'
import { useExamStore } from '@/stores/exam'
import { getExamSession, resumeExamSession } from '@/api/exam/examSessions'
import { getMyExamAssignments } from '@/api/exam/examAssignments'
import { getStudentExam } from '@/api/exam/exams'
import { submitExamAnswer, saveDraftAnswer } from '@/api/exam/examAnswers'
import { submitExam as submitExamSession } from '@/api/exam/examSessions'

const router = useRouter()
const route = useRoute()
const examStore = useExamStore()

const examId = route.params.id || '1' // 默认考试ID
const sessionId = route.query.sessionId // 从URL获取sessionId
const exam = ref({})
const examSession = ref({}) // 考试会话信息
const currentQuestionIndex = ref(0)
const answers = ref({})
const markedQuestions = ref([])
const remainingTime = ref(0)
const navCollapsed = ref(false)
const submitDialogVisible = ref(false)
const submitting = ref(false)
const autoSaving = ref(false)
const timer = ref(null)
const autoSaveTimer = ref(null)
const saveTimeout = ref(null)
const isSaving = ref(false)

const currentQuestion = computed(() => {
  return exam.value.questions?.[currentQuestionIndex.value]
})

const answeredCount = computed(() => {
  return Object.keys(answers.value).filter(key => {
    const answer = answers.value[key]
    if (Array.isArray(answer)) {
      return answer.length > 0 && answer.some(a => a !== '' && a !== null && a !== undefined)
    }
    return answer !== '' && answer !== null && answer !== undefined
  }).length
})

const unansweredCount = computed(() => {
  return exam.value.questionCount - answeredCount.value
})

const isTimeWarning = computed(() => {
  return remainingTime.value <= 600 && remainingTime.value > 300 // 10分钟到5分钟
})

const isTimeDanger = computed(() => {
  return remainingTime.value <= 300 // 5分钟以内
})

const getQuestionTypeLabel = (type) => {
  const labels = {
    single: '单选题',
    multiple: '多选题',
    boolean: '判断题',
    fill: '填空题',
    essay: '简答题'
  }
  return labels[type] || type
}

const getQuestionTypeTag = (type) => {
  const types = {
    single: 'primary',
    multiple: 'success',
    boolean: 'warning',
    fill: 'info',
    essay: 'danger'
  }
  return types[type] || 'primary'
}

const isQuestionAnswered = (index) => {
  const answer = answers.value[index]
  if (Array.isArray(answer)) {
    return answer.length > 0 && answer.some(a => a !== '' && a !== null && a !== undefined)
  }
  return answer !== '' && answer !== null && answer !== undefined
}

const formatTime = (seconds) => {
  if (seconds <= 0) return '00:00:00'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const loadExam = async () => {
  try {
    if (!sessionId) {
      ElMessage.error('缺少考试会话信息')
      router.push('/student/exams')
      return
    }
    
    // 获取考试会话信息
    const sessionResponse = await getExamSession({ sessionId })
    if (sessionResponse && sessionResponse.code === 200 && sessionResponse.data) {
      examSession.value = sessionResponse.data
      
      // 使用新的getStudentExam API获取考试详细信息（不包含答案）
      const examResponse = await getStudentExam(examId)
      if (examResponse && examResponse.code === 200 && examResponse.data) {
        const examData = examResponse.data
        exam.value = {
          id: examData.examId,
          name: examData.title,
          description: examData.description || '',
          duration: examData.durationMinutes || 0,
          questionCount: examData.questions ? examData.questions.length : 0,
          totalScore: examData.totalScore || calculateTotalScore(examData.questions || []),
          questions: transformQuestionsFromStudentAPI(examData.questions || [])
        }
        
        // 初始化或恢复答案
        initializeAnswers()
        restoreAnswersFromSession()
        
        // 设置剩余时间
        remainingTime.value = examSession.value.remainingTime || (exam.value.duration * 60)
        
        // 启动计时器
        startTimer()
        
        // 启动自动保存
        startAutoSave()
      } else {
        throw new Error(examResponse?.message || '获取考试信息失败')
      }
    } else {
      // throw new Error(sessionResponse?.message || '获取考试会话失败')
    }
  } catch (error) {
    console.error('加载考试失败:', error)
    ElMessage.error('加载考试失败: ' + (error.message || '请重试'))
    router.push('/student/exams')
  }
}

// 计算总分
const calculateTotalScore = (questions) => {
  return questions.reduce((total, q) => total + (q.score || 10), 0)
}

// 转换题目格式（原格式）
const transformQuestions = (questions) => {
  return questions.map((q, index) => {
    const question = q.question
    return {
      id: question.questionId,
      content: question.content,
      type: getQuestionTypeFromBackend(question.questionType),
      score: q.score || 10,
      options: question.options ? question.options.map(opt => ({
        key: String.fromCharCode(65 + opt.optionOrder), // A, B, C, D
        text: opt.content
      })) : [],
      blanks: question.questionType === 'fill_in' ? [{}] : [], // 填空题的空数
      maxLength: 1000 // 简答题最大长度
    }
  })
}

// 转换题目格式（新的学生API格式）
const transformQuestionsFromStudentAPI = (questions) => {
  return questions.map((examQuestion, index) => {
    const question = examQuestion.question
    return {
      id: question.questionId,
      examQuestionId: examQuestion.examQuestionId,
      content: question.content,
      type: getQuestionTypeFromBackend(question.questionType),
      score: examQuestion.score || 10,
      questionOrder: examQuestion.questionOrder,
      options: question.options ? question.options.map(opt => ({
        key: String.fromCharCode(65 + opt.optionOrder - 1), // A, B, C, D (optionOrder从1开始)
        text: opt.content
      })) : [],
      blanks: question.questionType === 'fill_in' ? [{}] : [], // 填空题的空数
      maxLength: 1000, // 简答题最大长度
      subject: question.subject,
      difficulty: question.difficulty
    }
  })
}

// 转换题目类型
const getQuestionTypeFromBackend = (backendType) => {
  const typeMap = {
    'single_choice': 'single',
    'multiple_choice': 'multiple',
    'fill_in': 'fill',
    'subjective': 'essay'
  }
  return typeMap[backendType] || 'single'
}

// 从会话中恢复答案
const restoreAnswersFromSession = () => {
  if (examSession.value.answers) {
    examSession.value.answers.forEach(answer => {
      const questionIndex = exam.value.questions.findIndex(q => q.id == answer.questionId)
      if (questionIndex !== -1) {
        try {
          const answerContent = JSON.parse(answer.answerContent)
          answers.value[questionIndex] = answerContent
        } catch (error) {
          // 如果不是JSON格式，直接使用原始内容
          answers.value[questionIndex] = answer.answerContent
        }
      }
    })
  }
}

const initializeAnswers = () => {
  exam.value.questions.forEach((question, index) => {
    if (question.type === 'multiple') {
      answers.value[index] = []
    } else if (question.type === 'fill') {
      answers.value[index] = new Array(question.blanks.length).fill('')
    } else {
      answers.value[index] = ''
    }
  })
}

const startTimer = () => {
  timer.value = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      // 时间到，自动提交
      autoSubmitExam()
    }
  }, 1000)
}

const startAutoSave = () => {
  autoSaveTimer.value = setInterval(() => {
    autoSaveProgress()
  }, 30000) // 每30秒自动保存一次
}

const autoSaveProgress = async () => {
  // 防重复提交检查
  if (isSaving.value || autoSaving.value) {
    return
  }
  
  try {
    autoSaving.value = true
    
    // 保存当前题目的答案
    const currentAnswer = answers.value[currentQuestionIndex.value]
    if (currentAnswer !== undefined && currentAnswer !== '' && currentAnswer !== null) {
      const currentQuestion = exam.value.questions[currentQuestionIndex.value]
      if (currentQuestion && sessionId) {
        const draftData = {
          sessionId: sessionId,
          examId: parseInt(examId),
          answers: [{
            questionId: currentQuestion.id,
            answerContent: typeof currentAnswer === 'object' ? JSON.stringify(currentAnswer) : String(currentAnswer),
            isDraft: true,
            answerTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
          }]
        }
        
        await saveDraftAnswer(draftData)
      }
    }
    
    setTimeout(() => {
      autoSaving.value = false
    }, 1000)
  } catch (error) {
    console.error('自动保存失败:', error)
    autoSaving.value = false
  }
}

const saveAnswer = async () => {
  // 实时保存答案到本地存储
  localStorage.setItem(`exam_${examId}_answers`, JSON.stringify(answers.value))
  
  // 防抖保存到服务器
  if (saveTimeout.value) {
    clearTimeout(saveTimeout.value)
  }
  
  saveTimeout.value = setTimeout(async () => {
    // 防重复提交检查
    if (isSaving.value) {
      return
    }
    
    try {
      isSaving.value = true
      const currentAnswer = answers.value[currentQuestionIndex.value]
      if (currentAnswer !== undefined && currentAnswer !== '' && currentAnswer !== null) {
        const currentQuestion = exam.value.questions[currentQuestionIndex.value]
        if (currentQuestion && sessionId) {
          const draftData = {
            sessionId: sessionId,
            examId: parseInt(examId),
            answers: [{
              questionId: currentQuestion.id,
              answerContent: typeof currentAnswer === 'object' ? JSON.stringify(currentAnswer) : String(currentAnswer),
              isDraft: true,
              answerTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
            }]
          }
          
          await saveDraftAnswer(draftData)
        }
      }
    } catch (error) {
      console.warn('保存答案到服务器失败:', error)
    } finally {
      isSaving.value = false
    }
  }, 1000) // 1秒防抖
}

const goToQuestion = (index) => {
  if (index >= 0 && index < exam.value.questionCount) {
    currentQuestionIndex.value = index
  }
}

const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

const nextQuestion = () => {
  if (currentQuestionIndex.value < exam.value.questionCount - 1) {
    currentQuestionIndex.value++
  }
}

const toggleMark = () => {
  const index = currentQuestionIndex.value
  const markIndex = markedQuestions.value.indexOf(index)
  
  if (markIndex > -1) {
    markedQuestions.value.splice(markIndex, 1)
  } else {
    markedQuestions.value.push(index)
  }
}

const toggleNavCollapse = () => {
  navCollapsed.value = !navCollapsed.value
}

const showSubmitDialog = () => {
  submitDialogVisible.value = true
}

const submitExamForm = async () => {
  // 防重复提交检查
  if (submitting.value) {
    console.warn('正在提交中，请勿重复提交')
    return
  }
  
  try {
    submitting.value = true
    
    // 准备所有答案数据
    const allAnswers = []
    Object.keys(answers.value).forEach(index => {
      const answer = answers.value[index]
      if (answer !== undefined && answer !== '' && answer !== null) {
        const question = exam.value.questions[index]
        if (question) {
          allAnswers.push({
            questionId: question.id,
            answerContent: typeof answer === 'object' ? JSON.stringify(answer) : String(answer),
            isDraft: false,
            answerTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
          })
        }
      }
    })
    
    // 提交考试答案
    const submitData = {
      sessionId: sessionId,
      examId: parseInt(examId),
      answers: allAnswers
    }
    
    const response = await submitExamAnswer(submitData)
    
    if (response && response.code === 200) {
      // 提交答案成功后，更新考试会话状态
      const sessionResponse = await submitExamSession({
        sessionId: sessionId
      })
      
      if (sessionResponse && sessionResponse.code === 200) {
        // 清理定时器
        stopTimers()
        
        // 清理本地存储
        localStorage.removeItem(`exam_${examId}_answers`)
        
        ElMessage.success('考试提交成功')
        
        // 跳转到结果页面
        router.push(`/student/exams`)
      } else {
        throw new Error(sessionResponse?.message || '更新考试状态失败')
      }
    } else {
      throw new Error(response?.message || '提交失败')
    }
    
  } catch (error) {
    console.error('提交考试失败:', error)
    ElMessage.error('提交失败：' + (error.message || '请重试'))
  } finally {
    submitting.value = false
  }
}



const autoSubmitExam = async () => {
  // 防重复提交检查
  if (submitting.value) {
    console.warn('正在提交中，跳过自动提交')
    return
  }
  
  try {
    // 先尝试提交
    await submitExamForm()
    
    // 提交成功后显示通知
    ElMessage.success('考试时间已到，系统已自动提交您的答案')
  } catch (error) {
    console.error('自动提交失败:', error)
    
    // 如果自动提交失败，给用户一个手动提交的机会
    try {
      await ElMessageBox.confirm(
        '考试时间已到，但自动提交失败。是否立即手动提交？',
        '提交失败',
        {
          confirmButtonText: '立即提交',
          cancelButtonText: '稍后处理',
          type: 'error'
        }
      )
      
      // 用户选择立即提交
      await submitExamForm()
    } catch (confirmError) {
      // 用户取消或再次失败
      if (confirmError === 'cancel') {
        ElMessage.warning('请尽快手动提交考试答案')
      } else {
        ElMessage.error('提交失败，请联系管理员')
      }
    }
  }
}

const stopTimers = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
  
  if (autoSaveTimer.value) {
    clearInterval(autoSaveTimer.value)
    autoSaveTimer.value = null
  }
  
  if (saveTimeout.value) {
    clearTimeout(saveTimeout.value)
    saveTimeout.value = null
  }
}

const handleBeforeUnload = (event) => {
  event.preventDefault()
  event.returnValue = '您正在进行考试，确定要离开吗？'
  return '您正在进行考试，确定要离开吗？'
}

const handleVisibilityChange = () => {
  if (document.hidden) {
    // 页面被隐藏，可能是切换标签页
    console.warn('检测到页面切换，这可能影响考试')
    // 这里可以添加防作弊逻辑
  }
}

// 监听答案变化
watch(answers, () => {
  saveAnswer()
}, { deep: true })

onMounted(() => {
  loadExam()
  
  // 添加页面离开提醒
  window.addEventListener('beforeunload', handleBeforeUnload)
  
  // 监听页面可见性变化
  document.addEventListener('visibilitychange', handleVisibilityChange)
  
  // 尝试恢复之前的答案
  const savedAnswers = localStorage.getItem(`exam_${examId}_answers`)
  if (savedAnswers) {
    try {
      answers.value = JSON.parse(savedAnswers)
    } catch (error) {
      console.error('恢复答案失败:', error)
    }
  }
})

onUnmounted(() => {
  stopTimers()
  window.removeEventListener('beforeunload', handleBeforeUnload)
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})
</script>

<style lang="scss" scoped>
.exam-page {
  min-height: 100vh;
  background: var(--neutral-50);
  padding: 20px;
}

.exam-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .exam-info {
    h1 {
      font-size: 24px;
      font-weight: 700;
      color: var(--neutral-700);
      margin-bottom: 12px;
    }
    
    .exam-meta {
      display: flex;
      gap: 24px;
      
      .meta-item {
        display: flex;
        align-items: center;
        gap: 6px;
        color: var(--neutral-600);
        font-size: 14px;
        
        i {
          color: var(--neutral-400);
        }
      }
    }
  }
  
  .exam-timer {
    text-align: center;
    
    .timer-display {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 24px;
      font-weight: 700;
      color: var(--neutral-700);
      padding: 12px 20px;
      background: var(--neutral-100);
      border-radius: 8px;
      transition: all 0.3s ease;
      
      &.warning {
        background: #fef3c7;
        color: #92400e;
      }
      
      &.danger {
        background: #fee2e2;
        color: #dc2626;
        animation: pulse 1s infinite;
      }
    }
    
    .timer-label {
      margin-top: 8px;
      font-size: 12px;
      color: var(--neutral-500);
    }
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

.exam-progress {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  
  .progress-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    
    .progress-text {
      font-size: 14px;
      color: var(--neutral-600);
    }
    
    .progress-percentage {
      font-size: 14px;
      font-weight: 600;
      color: var(--primary-600);
    }
  }
}

.exam-content {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 20px;
  align-items: start;
}

.question-nav {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 20px;
  
  .nav-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    h3 {
      font-size: 16px;
      font-weight: 600;
      color: var(--neutral-700);
    }
  }
  
  .nav-content {
    .nav-legend {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 8px;
      margin-bottom: 16px;
      
      .legend-item {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 12px;
        color: var(--neutral-600);
        
        .legend-dot {
          width: 12px;
          height: 12px;
          border-radius: 50%;
          
          &.answered {
            background: #10b981;
          }
          
          &.current {
            background: #3b82f6;
          }
          
          &.unanswered {
            background: var(--neutral-300);
          }
          
          &.marked {
            background: #f59e0b;
          }
        }
      }
    }
    
    .nav-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 8px;
      
      .nav-item {
        width: 36px;
        height: 36px;
        border: 1px solid var(--neutral-300);
        border-radius: 6px;
        background: white;
        color: var(--neutral-600);
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        
        &:hover {
          border-color: var(--primary-400);
          background: var(--primary-50);
        }
        
        &.current {
          background: #3b82f6;
          color: white;
          border-color: #3b82f6;
        }
        
        &.answered {
          background: #10b981;
          color: white;
          border-color: #10b981;
        }
        
        &.marked {
          background: #f59e0b;
          color: white;
          border-color: #f59e0b;
        }
        
        &.current.marked {
          background: linear-gradient(45deg, #3b82f6 50%, #f59e0b 50%);
        }
      }
    }
  }
}

.question-content {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  
  .question-card {
    .question-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      .question-number {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 18px;
        font-weight: 600;
        color: var(--neutral-700);
      }
    }
    
    .question-score {
      display: flex;
      align-items: center;
      gap: 4px;
      color: var(--primary-600);
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 20px;
    }
    
    .question-text {
      font-size: 16px;
      line-height: 1.6;
      color: var(--neutral-700);
      margin-bottom: 24px;
      
      :deep(img) {
        max-width: 100%;
        height: auto;
        border-radius: 6px;
      }
    }
    
    .question-options {
      .option-item {
        display: flex;
        align-items: flex-start;
        gap: 8px;
        padding: 12px 16px;
        margin-bottom: 8px;
        border-radius: 8px;
        transition: all 0.2s ease;
        
        &:hover {
          background: var(--neutral-50);
        }
        
        .option-key {
          font-weight: 600;
          color: var(--neutral-600);
          min-width: 20px;
        }
        
        .option-text {
          flex: 1;
          line-height: 1.5;
          
          :deep(img) {
            max-width: 100%;
            height: auto;
            border-radius: 4px;
          }
        }
      }
      
      .fill-item {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 16px;
        
        .fill-label {
          min-width: 80px;
          font-weight: 500;
          color: var(--neutral-600);
        }
        
        .el-input {
          flex: 1;
        }
      }
    }
  }
  
  .question-navigation {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid var(--neutral-200);
    
    .nav-center {
      .question-indicator {
        font-size: 14px;
        color: var(--neutral-500);
        font-weight: 500;
      }
    }
  }
}

.submit-summary {
  .summary-item {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 1px solid var(--neutral-100);
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      color: var(--neutral-600);
      font-weight: 500;
    }
    
    .value {
      color: var(--neutral-700);
      font-weight: 600;
      
      &.warning {
        color: #f59e0b;
      }
    }
  }
}

.submit-warning {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: #fef3c7;
  border-radius: 8px;
  margin: 16px 0;
  color: #92400e;
  
  i {
    font-size: 16px;
  }
}

.submit-notice {
  margin-top: 16px;
  padding: 16px;
  background: var(--neutral-50);
  border-radius: 8px;
  
  p {
    margin-bottom: 8px;
    font-weight: 600;
    color: var(--neutral-700);
  }
  
  ul {
    margin: 0;
    padding-left: 20px;
    color: var(--neutral-600);
    
    li {
      margin-bottom: 4px;
      font-size: 14px;
    }
  }
}

.auto-save-indicator {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #10b981;
  color: white;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  z-index: 1000;
  animation: fadeInOut 2s ease-in-out;
}

@keyframes fadeInOut {
  0%, 100% {
    opacity: 0;
    transform: translateY(-10px);
  }
  20%, 80% {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 1024px) {
  .exam-content {
    grid-template-columns: 1fr;
    
    .question-nav {
      position: static;
      order: 2;
    }
    
    .question-content {
      order: 1;
    }
  }
}

@media (max-width: 768px) {
  .exam-page {
    padding: 12px;
  }
  
  .exam-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
    
    .exam-meta {
      flex-direction: column;
      gap: 8px;
    }
  }
  
  .question-nav {
    .nav-legend {
      grid-template-columns: 1fr;
    }
    
    .nav-grid {
      grid-template-columns: repeat(6, 1fr);
      
      .nav-item {
        width: 32px;
        height: 32px;
        font-size: 12px;
      }
    }
  }
  
  .question-navigation {
    flex-direction: column;
    gap: 16px;
    
    .el-button {
      width: 100%;
    }
  }
}
</style>